package cn.zzf.controller;


import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * ${DESCRIPTION}
 *
 * @author GaoFeng2017
 * @date 2018-02-13 21:29:49
 **/

@WebServlet(name = "Captcha", urlPatterns = {"/Captcha"})

public class Captcha extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        CookieStore cookieStore = new BasicCookieStore();
        CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        HttpPost post = new HttpPost("http://218.65.5.214:2001/jwweb/sys/ValidateCode.aspx");
        HttpResponse execute = client.execute(post);
        HttpEntity entity = execute.getEntity();
        InputStream in = entity.getContent();
        List<Cookie> cookies = cookieStore.getCookies();
        Cookie cookie = cookies.get(0);
        request.getSession().setAttribute("sessionId",cookie.getValue());
        OutputStream ow =  response.getOutputStream();
        byte[] bys = new byte[10240];
        int i = 0;

        while ((i = in.read(bys)) != -1) {
            ow.write(bys,0,i);
        }

        in.close();
        ow.close();

    }
}
